﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using SqlSugarAndEntity.Entity;
using SqlSugarAndEntity.DataTransferObject.user;
using System.Collections.Generic;
using Core.ApiFilter.Attributes;
using System.Linq;
using System.IO;
using System;
using Lazy.Captcha.Core;
using Services.User;
using Common.IdCreator;
using Common.PasswordHelper;
using Core.CacheService.Interface;
using Microsoft.AspNetCore.Authorization;
using WebApi.Middlewares.Attributes;
using Common.ExpressionHelper;
using Microsoft.Extensions.DependencyInjection;
using Core.QuartzService;
using Services.Job;
using Common.NpoiHelper.Model;
using Common.NpoiHelper;
using System.Threading.Tasks;
using Serilog;
using System.Threading;
using SqlSugarAndEntity.DataTransferObject.Test;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "base_api")]
    [Authorize(Roles ="Admin")]
    public class UserController : ControllerBase
    {
        private IUserService userService;
        private readonly IMapper mapper;
        private IConfiguration configuration;
        private ICache cache;
        private readonly ICaptcha captcha;
        public UserController(IUserService userService, IMapper mapper, IConfiguration configuration, ICache cache, ICaptcha captcha)
        {
            this.userService = userService;
            this.mapper = mapper;
            this.configuration = configuration;
            this.cache= cache;
            this.captcha = captcha;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="Account"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [IgnoreLog]
        [HttpGet("Login")]
        public IActionResult Login(string Account,string pwd)
        {
            //var info= captcha.Generate("1");
            ////QuartzExtensions.ExcuteJob(typeof(TestJob));
            //NpoiHelper.CommentExcel(@"C:\Users\53205\Desktop\测试.xls", new List<CommentModel>()
            //{
            //    new CommentModel(){RowIndex=2,ColumnIndex=0,Message="测试批注1"},
            //    new CommentModel(){RowIndex=2,ColumnIndex=1,Message="测试批注11"},
            //    new CommentModel(){RowIndex=2,ColumnIndex=2,Message="测试批注11"},
            //    new CommentModel(){RowIndex=3,ColumnIndex=1,Message="测试批注2"},
            //});
            return Ok(userService.Login(Account, pwd));
        }
        /// <summary>
        /// 测试异步代理
        /// </summary>
        /// <returns></returns>
        [HttpGet("TestAsync")]
        [AllowAnonymous]
        [IgnoreLog]
        public async Task TestAsync()
        {
            //await userService.TestAsync(1);
            await userService.TestClassAsync();
            //userService.Test();
            //userService.TestClass();
            userService.TestProxy(new TestProxy()
            {
                testProxyChildren = new TestProxyChildren()
                {
                    Id = 1
                }
            });
        }
        /// <summary>
        /// 刷新token
        /// </summary>
        /// <returns></returns>
        [ApiIgnore]
        [AllowAnonymous]
        [HttpPost("RefreshToken")]
        public IActionResult RefreshToken([FromBody]JObject value) => Ok(userService.RefreshToken(value));
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="Name">用户姓名</param>
        /// <param name="UserAccount">用户账号</param>
        /// <param name="UserPhone">用户电话</param>
        /// <param name="IdNumber">用户ID</param>
        /// <param name="OrgName">用户组织机构名称</param>
        /// <param name="page">页码</param>
        /// <param name="limit">每页条数</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUserInfo(string Name, string UserAccount, string UserPhone, string IdNumber, string OrgName, int page, int limit)
            => Ok(userService.GetUserInfo(Name, UserAccount, UserPhone, IdNumber, OrgName, page, limit));
        /// <summary>
        /// 创建用户信息
        /// </summary>
        /// <param name="userDTO"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CreateUserInfo([FromBody] UserDTO userDTO)
        {
            string PwdKey = configuration.GetSection("AESKey").Value;
            List<sys_usermaporg> maps = new List<sys_usermaporg>();
            var userId= IDHelper.GetId();
            foreach (decimal orgid in userDTO.OrgId)
            {
                sys_usermaporg map = new sys_usermaporg()
                {
                    UserID = userId,
                    OrgID = orgid
                };
                maps.Add(map);
            }
            sys_userinfo user= mapper.Map<sys_userinfo>(userDTO);
            user.ID = userId;
            user.UserPassWord = AESHelper.AesEncrypt(user.UserPassWord, PwdKey);
            return Ok(userService.CreateUserInfo(user, maps));
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="userDTO"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdateUserInfo([FromBody] UserDTO userDTO)
        {
            string PwdKey = configuration.GetSection("AESKey").Value;
            List<sys_usermaporg> maps = new List<sys_usermaporg>();
            foreach (decimal orgid in userDTO.OrgId)
            {
                sys_usermaporg map = new sys_usermaporg()
                {
                    UserID = userDTO.ID,
                    OrgID = orgid
                };
                maps.Add(map);
            }
            sys_userinfo user = mapper.Map<sys_userinfo>(userDTO);
            user.UserPassWord = AESHelper.AesEncrypt(user.UserPassWord, PwdKey);
            return Ok(userService.UpdateUserInfo(user, maps));
        }
        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DeleteUserInfo(decimal userId)
            => Ok(userService.DeleteUserInfo(a=>a.ID==userId,b=>b.UserID==userId));
        /// <summary>
        /// 根据角色ID获取被授权的用户
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet("GetRoleAuthorized")]
        public IActionResult GetRoleAuthorized(decimal roleId, int page, int limit)
            => Ok(userService.GetRoleAuthorized(roleId, page, limit));

        /// <summary>
        /// 根据角色ID获取未被授权的用户
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet("GetRoleNotAuthorized")]
        public IActionResult GetRoleNotAuthorized(decimal roleId, int page, int limit)
            => Ok(userService.GetRoleNotAuthorized(roleId, page, limit));
        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="UserId">用户id</param>
        /// <param name="OldPwd">旧密码</param>
        /// <param name="NewPwd">新密码</param>
        /// <returns></returns>
        [HttpGet("UpdateUserPwd")]
        public IActionResult UpdateUserPwd(decimal UserId, string OldPwd, string NewPwd)
            => Ok(userService.UpdateUserPwd(UserId, OldPwd, NewPwd));
        /// <summary>
        /// 导出用户信息
        /// </summary>
        /// <param name="Name">用户姓名</param>
        /// <param name="UserAccount">用户账号</param>
        /// <param name="UserPhone">用户手机</param>
        /// <param name="IdNumber">身份证号码</param>
        /// <param name="OrgName">组织机构名称</param>
        /// <returns></returns>
        [HttpGet("ExportUserInfo")]
        public IActionResult ExportUserInfo(string Name, string UserAccount, string UserPhone, string IdNumber, string OrgName)
            => Ok(userService.ExportUserinfo(Name, UserAccount, UserPhone, IdNumber, OrgName));

    }
}
